<template>
  <div class="time-range-selector">
    <el-drawer
      v-model="visible"
      title="时间段选择"
      direction="rtl"
      size="400px"
    >
      <div class="selector-content">
        <!-- 预设时间段 -->
        <div class="section">
          <h4>预设时间段</h4>
          <div class="preset-grid">
            <el-button
              v-for="(preset, key) in presets"
              :key="key"
              :type="isSelectedPreset(key) ? 'primary' : 'default'"
              @click="selectPreset(key)"
              size="small"
            >
              {{ preset.label }}
            </el-button>
          </div>
        </div>

        <!-- 自定义范围 -->
        <div class="section">
          <h4>自定义范围</h4>
          <el-form :model="customRange" label-width="80px">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="customRange.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="customRange.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyCustomRange">应用</el-button>
              <el-button @click="resetCustomRange">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 统计信息 -->
        <div class="section">
          <h4>时间范围信息</h4>
          <div class="range-info">
            <p><strong>开始日期：</strong>{{ formatDate(selectedRange[0]) }}</p>
            <p><strong>结束日期：</strong>{{ formatDate(selectedRange[1]) }}</p>
            <p><strong>总天数：</strong>{{ getDaysCount() }} 天</p>
            <p><strong>总周数：</strong>{{ getWeeksCount() }} 周</p>
            <p><strong>总月数：</strong>{{ getMonthsCount() }} 个月</p>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="applyRange">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import dayjs from 'dayjs'

export default {
  name: 'TimeRangeSelector',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    currentRange: {
      type: Array,
      default: () => [dayjs().startOf('month'), dayjs().endOf('month')]
    }
  },
  emits: ['update:modelValue', 'range-change'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    const selectedRange = ref([...props.currentRange])
    const customRange = ref({
      startDate: props.currentRange[0],
      endDate: props.currentRange[1]
    })

    // 预设时间段
    const presets = {
      'today': {
        label: '今天',
        range: [dayjs().startOf('day'), dayjs().endOf('day')]
      },
      'this-week': {
        label: '本周',
        range: [dayjs().startOf('week'), dayjs().endOf('week')]
      },
      'next-week': {
        label: '下周',
        range: [dayjs().add(1, 'week').startOf('week'), dayjs().add(1, 'week').endOf('week')]
      },
      'current-month': {
        label: '本月',
        range: [dayjs().startOf('month'), dayjs().endOf('month')]
      },
      'last-month': {
        label: '上月',
        range: [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')]
      },
      'next-month': {
        label: '下月',
        range: [dayjs().add(1, 'month').startOf('month'), dayjs().add(1, 'month').endOf('month')]
      },
      'current-quarter': {
        label: '本季度',
        range: [dayjs().startOf('quarter'), dayjs().endOf('quarter')]
      },
      'last-quarter': {
        label: '上季度',
        range: [dayjs().subtract(1, 'quarter').startOf('quarter'), dayjs().subtract(1, 'quarter').endOf('quarter')]
      },
      'current-year': {
        label: '本年',
        range: [dayjs().startOf('year'), dayjs().endOf('year')]
      },
      'last-year': {
        label: '去年',
        range: [dayjs().subtract(1, 'year').startOf('year'), dayjs().subtract(1, 'year').endOf('year')]
      },
      'last-7-days': {
        label: '最近7天',
        range: [dayjs().subtract(7, 'days'), dayjs()]
      },
      'last-30-days': {
        label: '最近30天',
        range: [dayjs().subtract(30, 'days'), dayjs()]
      },
      'next-30-days': {
        label: '未来30天',
        range: [dayjs(), dayjs().add(30, 'days')]
      }
    }



    // 选择预设时间段
    const selectPreset = (key) => {
      const preset = presets[key]
      if (preset) {
        selectedRange.value = [preset.range[0], preset.range[1]]
        customRange.value = {
          startDate: preset.range[0],
          endDate: preset.range[1]
        }
      }
    }



    // 应用自定义范围
    const applyCustomRange = () => {
      if (customRange.value.startDate && customRange.value.endDate) {
        selectedRange.value = [customRange.value.startDate, customRange.value.endDate]
      }
    }

    // 重置自定义范围
    const resetCustomRange = () => {
      customRange.value = {
        startDate: props.currentRange[0],
        endDate: props.currentRange[1]
      }
      selectedRange.value = [...props.currentRange]
    }

    // 应用范围
    const applyRange = () => {
      emit('range-change', selectedRange.value)
      visible.value = false
    }

    // 检查是否选中预设
    const isSelectedPreset = (key) => {
      const preset = presets[key]
      if (!preset) return false
      return selectedRange.value[0].isSame(preset.range[0], 'day') && 
             selectedRange.value[1].isSame(preset.range[1], 'day')
    }



    // 格式化日期
    const formatDate = (date) => {
      return date.format('YYYY-MM-DD')
    }

    // 计算天数
    const getDaysCount = () => {
      return selectedRange.value[1].diff(selectedRange.value[0], 'day') + 1
    }

    // 计算周数
    const getWeeksCount = () => {
      return Math.ceil(getDaysCount() / 7)
    }

    // 计算月数
    const getMonthsCount = () => {
      return selectedRange.value[1].diff(selectedRange.value[0], 'month') + 1
    }

    // 监听当前范围变化
    watch(() => props.currentRange, (newRange) => {
      selectedRange.value = [...newRange]
      customRange.value = {
        startDate: newRange[0],
        endDate: newRange[1]
      }
    }, { deep: true })

    return {
      visible,
      selectedRange,
      customRange,
      presets,
      selectPreset,
      applyCustomRange,
      resetCustomRange,
      applyRange,
      isSelectedPreset,
      formatDate,
      getDaysCount,
      getWeeksCount,
      getMonthsCount
    }
  }
}
</script>

<style scoped>
.time-range-selector {
  /* 组件样式 */
}

.selector-content {
  padding: 20px;
}

.section {
  margin-bottom: 30px;
}

.section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.preset-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
  gap: 8px;
  margin-left: 10px;
}

.preset-grid .el-button {
  width: 100%;
  height: 32px;
  font-size: 12px;
}

.preset-grid .el-button:nth-child(1) {
  margin-left: 12px;
}

.range-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.range-info p {
  margin: 8px 0;
  font-size: 14px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}
</style> 